package com.jason.quectel.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author：Jason
 * @date：2022/3/9 16:22
 * @email：1129847330@qq.com
 * @description:
 */
public class HttpUtils {
    private static final String TAG = "HttpUtils";

    /**
     * @param address
     * @return
     * @throws IOException
     */
    public static String get(String address) throws IOException {
        URL url = new URL(address);
        //得到connection对象。
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //设置请求方式
        connection.setRequestMethod("GET");
        //设置一个自定义的请求头:action，由于后端判断
        connection.setRequestProperty("action", "quectel");
        //支持从服务端读取结果流，默认为true
        connection.setDoOutput(true);
        //禁用缓存
        connection.setUseCaches(false);
        //连接
        connection.connect();
        //得到响应码
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            //得到响应流
            InputStream inputStream = connection.getInputStream();
            //将响应流转换成字符串
            String result = is2String(inputStream);
            return result;
        }
        return "";
    }

    /**
     * @param address
     * @param params  userName=zhangsan&password=123456
     * @return
     * @throws IOException
     */
    public static String post(String address, String params) throws IOException {
        URL url = new URL(address);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.connect();

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
        writer.write(params);
        writer.close();

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
            return is2String(inputStream);
        }
        return "";
    }

    public static String is2String(InputStream is) throws IOException {
        //连接后，创建一个输入流来读取response
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "utf-8"));
        String line = "";
        StringBuilder stringBuilder = new StringBuilder();
        String response = "";
        //每次读取一行，若非空则添加至 stringBuilder
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
        //读取所有的数据后，赋值给 response
        response = stringBuilder.toString().trim();
        return response;
    }
}